import { Injectable } from '@nestjs/common';
import { join } from 'path';
import * as fs from 'fs';
import { v1 } from 'node-uuid';
import { InjectRepository } from '@nestjs/typeorm';
import { Bk_File_Manage } from './bk_file_manage.entity';
import { Repository, Like } from 'typeorm';
import { exec, execSync } from 'child_process';
@Injectable()
export class FileManageService {
    constructor(
        @InjectRepository(Bk_File_Manage)
        private readonly fileManageRepository: Repository<Bk_File_Manage>,
    ) { }

    async upload(files: any): Promise<any> {
        let result = [];
        for (let i = 0; i < files.videos.length; i++) {
            const file_path = v1() + '.' + (files.videos[i].originalname).split('.')[1];
            const path = join(__dirname, '..', 'public', 'video', file_path);
            fs.writeFileSync(path, files.videos[i].buffer);
            const info = execSync('ffprobe -select_streams v -show_entries format=duration,size,bit_rate -show_streams -show_format -v quiet -of csv="p=0" -of json -i ' + path).toString('utf-8')
            const videoInfo = JSON.parse(info);
            const file_preview_picture_name = v1() + '.jpg';
            const file_preview_picture_path = join(__dirname, '..', 'public', 'image', file_preview_picture_name)
            exec('ffmpeg -i ' + path + ' -ss 1 -f image2 ' + file_preview_picture_path);
            result.push(
                await this.fileManageRepository.save({
                    file_name: decodeURIComponent(files.videos[i].originalname.split('.')[0]),
                    file_path,
                    file_size: videoInfo.format.size,
                    file_duration: videoInfo.format.duration,
                    file_type: videoInfo.streams[0].codec_type,
                    file_preview_picture: file_preview_picture_name,
                    file_width: videoInfo.streams[0].width,
                    file_height: videoInfo.streams[0].height
                })
            );
        }
        return result;
    }

    async findAll(query: any): Promise<[Bk_File_Manage[], number]> {
        return await this.fileManageRepository.findAndCount({
            skip: query.skip,
            take: query.take
        });
    }

    async getVideosByName(query: any): Promise<[Bk_File_Manage[], number]> {
        return await this.fileManageRepository.findAndCount({
            where: { file_name: Like("%" + query.name + "%") },
            skip: query.skip,
            take: query.take,
        });
    }

    async delete(body: any) {
        const { file_path } = await this.fileManageRepository.findOne({ where: { id: body.id }, select: ['file_path'] });
        const res = await this.fileManageRepository.delete({ id: body.id });
        fs.unlinkSync(join(__dirname, '..', 'public', 'video', file_path));
        return res
    }
}